<?php
namespace app\model;


class Fee {

    static function commHand($comm,$system){
        global $_G;
        if(empty($comm)){
            return array("1","记录不存在");
        }
        if($comm['status']==1){
            return array("1","已经成功发放奖金");
        }
        $themeid = $comm['themeid'];
        $theme = Theme::getThemeById($themeid);
        $config = 	Theme::getConfig($themeid);
        $desc = '推荐赏金';
        $data['status']=1;
        $data['msg']="手动发放";
        db_update(t_comm,$data, array('id' => $comm['id']));
        $fans = db_find ( "SELECT * FROM ".tablename("mc_mapping_fans")." 
							WHERE openid = :openid",array(":openid"=>$comm['openid']));
        $member = db_find ( "SELECT * FROM ".tablename("mc_members")."
							WHERE uid = :uid",array(":uid"=>$fans['uid']));
        $rdata = array(
            'uniacid'  => $_G['mpid'],
            'ordertype'=> 2,
            'ordersn'  => $comm['ordersn'],
            'tid'      => '1'.$comm['ordersn'],
            'themeid'  => $themeid,
            'openid'   => $comm['openid'],
            'uid'	    => $member['uid'],
            'username' => $member['realname'],
            'mobile'   => $member['mobile'],
            'addtime'  => TIMESTAMP,
            'type'     => 'cash',
            'orderfee' => $comm['fee']*(-1),
            'realfee'  => $comm['fee']*(-1),
            'paystate' =>1,
            'status'   =>1,
            'paytime'  =>TIMESTAMP
        );
        $rdata['masterid'] = $comm['id'];
        db_insert (t_order,$rdata);
        $orderid = $insertid;
        if($orderid <= 0){
            return_msg('定单数据错误');
        }
        if($system['noticeopen'] == 1){
            $record = db_find ( "SELECT * FROM ".tablename(t_record)." WHERE  id ='{$comm['recordid']}'" );
            $url2 = $_G['siteroot'].'app/index.php?i='.$_G['mpid'].'&c=entry&themeid='.$themeid.'&do=index&m='.MODULE_NAME;
            $message = array(
                "url"       =>$url2,
                "openid"    =>$comm['openid'],
                "first"     =>$member['realname'].'您好，您推荐'.$record['username'].'的赏金已成功发放！',
                "keyword1"  =>'￥'.$comm['fee'],
                "keyword2"  =>'管理员手动发放',
                "keyword3"  =>date('Y-m-d  H:i:s',$comm['addtime']),
                "keyword4"  =>'审核通过',
                "keyword5"  =>date('Y-m-d H:i:s'),
                "remark"    =>!empty($system['attendok_remark']) ?$system['attendok_remark']:'感谢你的参与，点击查看活动详情,客服电话:'.$theme['tel'],
            );
            $r = Util::sendWithdrawNotice($message,$system);
        }
        return array("0","发放成功");
    }

    static function match_chinese($chars,$encoding='utf8')
    {
    $pattern =($encoding=='utf8')?'/[\x{4e00}-\x{9fa5}a-zA-Z0-9]/u':'/[\x80-\xFF]/';
    preg_match_all($pattern,$chars,$result);
    $temp =join('',$result[0]);
    return $temp;
    }


    static function commRecord($comm,$system){
        global $_G;
        if(empty($comm)){
            return array("1","记录不存在");
        }
        if($comm['status']==1 || $comm['status']==99){
            return array("1","已经成功发放奖金");
        }
        if ($comm['fee']<0.3) {
            return array("1","最小提现金额为0.3元");
        }

        $themeid = $comm['themeid'];
        $theme = Theme::getThemeById($themeid);
        $config = 	Theme::getConfig($themeid);
        $fromfans = Fans::getById($comm['fromuid'],$themeid);
        $fromtext = '【'.$fromfans['username']."】".$fromfans['mobile'];
        if ($comm['type']==4){
            $desc = '转发红包';
        }elseif ($comm['type']==6){
            $desc = '提成'.$fromtext;
        }elseif ($comm['type']==7){
            $desc = '摇一摇红包';
        }elseif ($comm['type']==2){
            $desc = '二级红包'.$fromtext;
        }elseif ($comm['type']==3){
            $desc = '三级红包'.$fromtext;
        }elseif ($comm['type']==5){
            $desc = '阅读红包'.'【'.Fee::match_chinese($fromfans['nickname']).'】';
        }else{
            $desc = '红包'.$fromtext;
        }
        if (in_array($comm['type'], array(4,5,6,7,99))){
            $ordertype = $comm['type'];
        }else{
            $ordertype = 2;
        }
        if ($comm['type']==99){
            $status =99;
        }else{
            $status =1;
        }

        if ($comm['type']==10 || $comm['type']==11){
            return_msg('此类红包不可发放');
        }

        if($system['autored']== 3 ){
            return_msg('红包发放未开启');
        }

        $txresult = Util::transfer($comm['openid'],$comm['fee'],$comm['ordersn'],$desc,$system);
        if($txresult['code'] == 0){
            $data= array();
            $data['status']=$status;
            $data['msg']="自动发放";
            db_update(t_comm,$data, array('id' => $comm['id']));
            //手动提现
            if ($comm['type']==99){
                $commlist = explode(',', $comm['city']);
                if (!empty($commlist)) {
                    foreach ($commlist as $index => $row) {
                        $data= array();
                        $data['status']=1;
                        $data['msg']="手动提现：" . $comm['id'];
                        db_update(t_comm,$data, array('id' =>$row));
                    }
                }
            }

            db_query("UPDATE ".tablename(t_fans)." SET feesum = feesum + " . $comm['fee'] . ", commcount = commcount + 1 WHERE uniacid = " . $comm['uniacid'] ." and themeid =" . $comm['themeid'] ." and uid = " . $comm['uid'] );
        
            $p = array(":uniacid"=>$comm['uniacid'],":themeid"=>$comm['themeid']);
            db_query("UPDATE ".tablename(t_theme)." SET commcount = commcount + " . $comm['fee'] . " WHERE uniacid = :uniacid and id =:themeid",$p);
            
            //如果是员工的话统计今日收到的红包数
            $isworker = Worker::getThemeWorkerByOpenidNew($comm['openid'],$themeid);
            if (!empty($isworker)){
                Theme::workerreport($comm['themeid'],$comm['uid'],array('comm' =>$comm['fee']));
            }

            $fans = db_find ( "SELECT * FROM ".tablename("mc_mapping_fans")." 
							WHERE openid = :openid",array(":openid"=>$comm['openid']));
            $member = db_find ( "SELECT * FROM ".tablename("mc_members")."
							WHERE uid = :uid",array(":uid"=>$fans['uid']));

            $rdata = array(
                'uniacid'  => $_G['mpid'],
                'ordertype'=> $ordertype,
                'ordersn'  => $comm['ordersn'],
                'tid'      => '1'.$comm['ordersn'],
                'themeid'  => $themeid,
                'openid'   => $comm['openid'],
                'uid'	    => $member['uid'],
                'username' => $member['realname'],
                'mobile'   => $member['mobile'],
                'addtime'  => TIMESTAMP,
                'type'     => 'wechat',
                'orderfee' => $comm['fee']*(-1),
                'realfee'  => $comm['fee']*(-1),
                'paystate' =>1,
                'status'   =>1,
                'paytime'  =>TIMESTAMP
            );
            $rdata['masterid'] = $comm['id'];
            db_insert (t_order,$rdata);
            $orderid = $insertid;
            if($orderid <= 0){
                return_msg('定单数据错误');
            }
            if($system['noticeopen'] == 1){
                $record = db_find ( "SELECT * FROM ".tablename(t_record)." WHERE  id ='{$comm['recordid']}'" );
                $url2 = $_G['siteroot'].'app/index.php?i='.$_G['mpid'].'&c=entry&themeid='.$themeid.'&do=index&m='.MODULE_NAME;
                $message = array(
                    "url"       =>$url2,
                    "openid"    =>$comm['openid'],
                    "first"     =>$member['realname'].'您好，您推荐'.$record['username'].'的赏金已成功发放！',
                    "keyword1"  =>'￥'.$comm['fee'],
                    "keyword2"  =>'提现到微信余额',
                    "keyword3"  =>date('Y-m-d  H:i:s',$comm['addtime']),
                    "keyword4"  =>'审核通过',
                    "keyword5"  =>date('Y-m-d H:i:s'),
                    "remark"    =>!empty($system['attendok_remark']) ?$system['attendok_remark']:'感谢你的参与，点击查看活动详情,客服电话:'.$theme['tel'],
                );
                $r = Util::sendWithdrawNotice($message,$system);
            }
            return array("0","发放成功");
        }else{
            db_update(t_comm,array("msg"=>$txresult['message']), array('id' => $comm['id']));
            return array("1",'失败：'.$txresult['message']);
        }

    }

	static function getById($id) {
	    if (empty($id)) {
			return false;
		}
		$sql = "SELECT * FROM " . tablename(t_fee) . " where id = :id";
		$row = db_find($sql, array(":id"=>$id));
		return $row;
	}

    static function getUnPayList(){
        global $_G, $_P;
        $list = db_select( "SELECT * FROM " . tablename (t_fee) . " WHERE status = 0 order by id limit 1" );
        return $list;
    }

    static function getUnPayOneItem() {
        global $_G, $_P;
        $sql = "SELECT * FROM " . tablename (t_fee) . " WHERE status = 0 order by id limit 1" ;
        $row = db_find($sql);
        $row['sql'] = $sql;
        $row['param'] =$p;
        return $row;
    }


    static function getFeeRank($themeid){
        $p = array(":themeid"=>$themeid);

        $sql = "SELECT m.openid,m.uid,sum(fee) as feesum,count(m.id) as commcount,f.avatar,f.nickname FROM ".tablename(t_fee)." as m
							left join ".tablename(t_member)." as f on f.openid = m.openid
				WHERE m.themeid = :themeid and m.status = 1 group by m.openid,m.uid order by feesum desc limit 20";

        $commslist = db_select($sql,$p);
        return $commslist;
    }

    static function getFeeSum($openid,$themeid) {
        if (empty($openid)) {
            return false;
        }
        $pm = array(":themeid"=>$themeid,":openid"=>$openid);
        $sql = "SELECT sum(fee)  FROM ".tablename(t_fee)."
				WHERE themeid = :themeid and openid = :openid and status = 1";
        $commssum = floatval(db_fetchcolumn($sql,$pm));
        return $commssum;
    }

	static function deleteById($id){
        if (empty($id)) {
            return false;
        }
        db_delete ( t_fee, array ('id' => $id) );
        return true;
    }


	static function getListByCondition($condition,$pageNumber,$pageSize){
        $sql = "SELECT master.*,t.title as theme,tt.nickname as fnickname,tt.avatar as favatar,tt.username as fusername,tt.mobile as fmobile FROM " . tablename ( t_fee ) . " as master
                        left join " . tablename ( t_theme ) . " as t on t.id = master.themeid
                        left join " . tablename ( t_order ) . " as tt on tt.id = master.orderid
						WHERE   {$condition} ORDER BY master.id desc
									LIMIT " . ($pageNumber - 1) * $pageSize . ',' . $pageSize;
        $list = db_select ( $sql );
        return $list;

    }

    static function getIncomeByThemeId($themeid){
        $income = db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_fee ) . "
				WHERE themeid = :themeid and paystate = 1 and ordertype = 'theme' and orderfee > 0 ", array(":themeid"=>$themeid) );
        return floatval($income);
    }

    static function getOutcomeByThemeId($themeid){
        $income = db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_fee ) . "
				WHERE themeid = :themeid and paystate = 1 and ordertype = 'comm' and orderfee < 0 ", array(":themeid"=>$themeid) );
        return floatval($income);
    }


    static function getNumByCondition($condition){
        return db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_fee ) . " as master
					WHERE  {$condition} ORDER BY master.id" );

    }


    static function getCommByOpenId($id,$openid) {
        if (empty($id)) {
            return false;
        }
        $sql = "SELECT * FROM " . tablename(t_fee) . " 
                        where  openid = :openid and paystate = 1 and ordertype = 'comm' order by id desc";
        $row = db_select($sql, array(":openid"=>$openid));
        return $row;
    }


    static function getCommNumByOpenid($openid,$uniacid){
        $params = array();
        $params[':uniacid'] = $uniacid;
        $params[':openid'] = $openid;
        $point = db_fetchcolumn("SELECT count(*) FROM ".tablename(t_fee)."
			WHERE uniacid= :uniacid and openid = :openid and paystate = 1 and ordertype ='comm'",$params);
        return intval($point);
    }

    static function getOrderSumByOpenid($openid,$uniacid){
        $params = array();
        $params[':uniacid'] = $uniacid;
        $params[':openid'] = $openid;
        $point = db_fetchcolumn("SELECT count(*) FROM ".tablename(t_fee)."
			WHERE uniacid= :uniacid and openid = :openid and status >= 0",$params);
        return intval($point);
    }

    static function getByPaystateOrderId($id) {
        if (empty($id)) {
            return false;
        }
        $sql = "SELECT * FROM " . tablename(t_fee) . " 
                        where orderid = :id and paystate = 1 and ordertype = 'repair' order by id desc";
        $row = db_find($sql, array(":id"=>$id));
        return $row;
    }
    static function getByOrderIdAndOpenid($themeid,$orderid,$openid) {
        if (empty($openid) || empty($orderid) || empty($themeid)) {
            return false;
        }
        $sql = "SELECT * FROM " . tablename(t_fee) . " 
                        where themeid = :themeid and masterid = :masterid and openid = :openid 
                                and orderfee > 0 and ordertype = 'theme' order by id desc limit 1";
        $row = db_find($sql, array(":themeid"=>$themeid,":masterid"=>$orderid,":openid"=>$openid));
        return $row;
    }
    static function getByOrderId($id,$openid) {
        if (empty($id)) {
            return false;
        }
        $sql = "SELECT * FROM " . tablename(t_fee) . " 
                        where orderid = :id and openid = :openid and paystate = 1 and ordertype = 'order' order by id desc";
        $row = db_find($sql, array(":id"=>$id,":openid"=>$openid));
        return $row;
    }
    static function getByMixId($openid,$orderid,$uniacid){
        if (empty($openid) || empty($orderid) || empty($uniacid)) {
            return false;
        }
        $sql = "SELECT * FROM " . tablename(t_fee) . " 
                        where openid = :openid and orderid =:orderid and uniacid =:uniacid order by id desc";
        $row = db_find($sql, array(":openid"=>$openid,":orderid"=>$orderid,":uniacid"=>$uniacid));
        return $row;

    }
}
?>